import asyncio
import json
from datetime import datetime
import queue

# 交互模块：处理用户输入和命令

# 全局标志
user_initiated_exit = False
is_recording = False

class UserInteraction:
    def __init__(self):
        self.audio_player = None
        self.recording_handler = None
        self.websocket = None
        
        # 在初始化时就写入日志，确认类被正确实例化
        try:
            with open('interaction_init_log.txt', 'w') as log_file:
                log_file.write(f"交互模块初始化 - {datetime.now()}\n")
                log_file.flush()
            print("[DEBUG] 交互模块已初始化")
        except Exception as e:
            print(f"[ERROR] 交互模块初始化时写入日志失败: {e}")
    
    def set_components(self, audio_player, recording_handler):
        self.audio_player = audio_player
        self.recording_handler = recording_handler
    
    # 发送消息任务
    async def send_messages(self, websocket):
        """改进的交互任务，使用队列在主事件循环中发送消息"""
        # 导入必要的模块
        import sys
        import threading
        
        print("\n[DEBUG] send_messages 任务已启动")
        print("======================================")
        print("📢 用户交互已就绪！")
        print("📝 请输入您的消息，按Enter发送")
        print("🎤 输入'r' 开始/停止录音")
        print("🚪 输入'q' 退出程序")
        print("======================================\n")
        sys.stdout.flush()  # 强制刷新输出缓冲区
        
        # 初始化全局变量
        global user_initiated_exit, is_recording
        user_initiated_exit = False
        is_recording = False
        
        # 创建消息队列，用于在输入线程和主事件循环之间传递消息
        message_queue = queue.Queue()
        
        # 创建一个简单的线程来处理用户输入
        def input_thread():
            global user_initiated_exit, is_recording
            print("[DEBUG] 输入线程已启动")
            sys.stdout.flush()
            while not user_initiated_exit:
                try:
                    # 获取用户输入
                    user_input = input("💬 > ")
                    print(f"[DEBUG] 收到输入: {user_input}")
                    
                    # 处理不同的命令
                    if user_input.lower() == 'q':
                        print("\n[INFO] 正在退出程序...")
                        user_initiated_exit = True
                        break
                    elif user_input.lower() == 'r':
                        is_recording = not is_recording
                        if is_recording:
                            print("🎤 [录音中] 再次输入 'r' 停止录音")
                        else:
                            print("⏹️  [已停止录音]")
                    elif user_input.strip():
                        # 将消息放入队列，由主事件循环处理发送
                        dataJson = { 
                            "type": "listen",
                            "state": "detect",
                            "text": user_input,
                            "source": "text" 
                        }
                        message_queue.put(dataJson)
                    
                except EOFError:
                    # 处理输入流结束的情况
                    print("\n[WARN] 输入流已关闭")
                    break
                except KeyboardInterrupt:
                    print("\n[INFO] 检测到键盘中断")
                    user_initiated_exit = True
                    break
                except Exception as e:
                    print(f"[ERROR] 输入处理错误: {e}")
        
        # 启动输入线程
        thread = threading.Thread(target=input_thread, daemon=True)
        thread.start()
        
        # 主事件循环同时负责处理队列中的消息和监控退出信号
        try:
            while not user_initiated_exit:
                # 检查队列中是否有消息需要发送
                try:
                    if not message_queue.empty():
                        dataJson = message_queue.get_nowait()
                        await websocket.send(json.dumps(dataJson))
                        print("✅ 消息已发送")
                except queue.Empty:
                    pass
                except Exception as e:
                    print(f"[ERROR] 发送消息失败: {e}")
                
                # 让出控制权一小段时间
                await asyncio.sleep(0.1)
        except asyncio.CancelledError:
            print("[INFO] 交互任务被取消")
        except Exception as e:
            print(f"[ERROR] 交互任务主循环异常: {e}")
        finally:
            print("[INFO] 交互任务已退出")
    
    # 获取全局状态
    def get_state(self):
        global user_initiated_exit, is_recording
        return {
            'user_initiated_exit': user_initiated_exit,
            'is_recording': is_recording
        }
    
    # 设置录音状态
    def set_recording_state(self, state):
        global is_recording
        is_recording = state